import { pool } from '../db'


export interface QueryHotArticlesResponse {
  data: any[]
  total: number
  page: number
  pageSize: number
}

/**
 * 从数据库获取 WordPress 文章列表
 */
export async function fetchWpPosts(page = 1, pageSize = 10): Promise<QueryHotArticlesResponse> {
  const client = await pool.getConnection()

  try {
    const pageNum = parseInt(page as any)
    const size = parseInt(pageSize as any)
    const offset = (pageNum - 1) * size

    // 添加查询条件：push_status='publish' 以及 post_type='post' 或 post_type='cool_timeline'
    const query = `
      SELECT * 
      FROM wp_posts 
      WHERE post_status = 'publish' 
      AND (post_type = 'post' OR post_type = 'cool_timeline')
      ORDER BY post_date DESC 
      LIMIT ? OFFSET ?
    `
    const countQuery = `
      SELECT COUNT(*) as total
      FROM wp_posts
      WHERE post_status = 'publish' 
      AND (post_type = 'post' OR post_type = 'cool_timeline')
    `

    // 执行查询时传入分页参数
    const [result, countResult] = await Promise.all([
      client.query(query, [size, offset]),
      client.query(countQuery),
    ])

    return {
      data: Array.isArray(result[0]) ? result[0] : [],
      total: countResult[0][0].total,
      page: pageNum,
      pageSize: size,
    }
  } finally {
    client.release()
  }
}